<template>
    <div class="content manifest-list">
        <div class="content-top">
            <Button class="icon-btn" type="primary" @click="addOriginal">新增原始舱单</Button>
            <Button class="icon-btn" type="primary" @click="addPreplan">新增预配舱单</Button>
            <Button class="icon-btn" @click="handleBatchDeclaration">批量申报</Button>
            <!-- <Button class="icon-btn" type="primary" @click="importHandle">导入</Button> -->
            <SearchExpand>
                <Form v-model="searchData" class="clearfix" :label-width="88">
                    <FormItem label="舱单类型">
                        <Select v-model="searchData.manifestType" placeholder="请选择舱单类型">
                            <Option
                                v-for="(item, key) in manifestTypeList"
                                :key="key"
                                :value="key"
                                :label="item"
                            ></Option>
                        </Select>
                    </FormItem>
                    <FormItem label="批次号">
                        <Input v-model="searchData.cargoBatchNo" placeholder="请输入批次号"/>
                    </FormItem>
                    <FormItem label="提运单号">
                        <Input v-model="searchData.billNo" placeholder="请输入提运单号"/>
                    </FormItem>
                    <FormItem label="申报时间">
                        <DatePicker
                            :value="searchData.time1"
                            format="yyyy-MM-dd"
                            type="daterange"
                            placement="bottom-start"
                            placeholder="请选择申报时间"
                            @on-change="time1Change"
                        >
                        </DatePicker>
                    </FormItem>
                    <FormItem label="创建时间">
                        <DatePicker
                            :value="searchData.time2"
                            format="yyyy-MM-dd"
                            type="daterange"
                            placement="bottom-start"
                            placeholder="请选择创建时间"
                            @on-change="time2Change"
                        >
                        </DatePicker>
                    </FormItem>
                    <FormItem>
                        <Button class="icon-btn" type="primary" @click="getData">
                            <i class="iconfont icon-sousuo"></i> 查询
                        </Button>
                    </FormItem>
                </Form>
            </SearchExpand>
        </div>
        <div class="content-body">
            <Table
                :columns="tableColumns"
                :loading="loading"
                :data="tableList"
                @on-select="handleTableSelect"
                @on-select-cancel="handleTableSelectCancel"
                @on-selection-change="handleTableSelectChange"
                @on-expand="expandHandle"
            ></Table>
        </div>
        <Pagination
            :pageSize.sync="searchData.pageSize"
            :current.sync="searchData.pageNum"
            :total="searchData.total"
            @change="queryManifestList"
        />

        <importModal @reGetData="reGetData" ref="importModalRef"/>
        <Modal
            width="600px"
            title="申报失败"
            v-model="errorVisible"
        >
            <Table :height="330" :data="erorList" :columns="erorColumns"></Table>
            <div slot="footer">
                <Button @click="errorVisible = false">关闭</Button>
                <Button @click="carryOnBatchDeclaration" type="primary" v-if="errorType === 'warn'" :loading="continueLoading">继续申报</Button>
            </div>
        </Modal>
        <!-- 申报结果 -->
        <Modal width="450px" v-model="resultModal.visible" footer-hide :closable="false">
            <div>
                <div class="result-modal-header">
                    <Icon v-if="resultModal.failNum > 0" type="ios-alert" color="#f90" :size="28"></Icon>
                    <Icon v-else type="ios-checkmark-circle" color="#19be6b" :size="28"></Icon>
                    <span class="result-modal-header-title">{{resultModal.title}}</span>
                </div>
                <div class="result-modal-content" v-if="resultModal.failNum > 0">
                    <p>
                        <span class="success">{{resultModal.successNum}}</span> 条舱单申报成功
                    </p>
                    <p>
                        <span class="error">{{resultModal.failNum}}</span> 条舱单申报失败
                    </p>
                    <p>
                        失败批次号：{{resultModal.failInenerNo}}
                    </p>
                </div>
                <div class="result-modal-content" v-else>
                    批量申报成功！
                </div>
                <div class="result-modal-content-footer">
                    <Button type="primary" @click="closeResultModal">关闭</Button>
                </div>
            </div>
        </Modal>
    </div>
</template>

<script>
import { getManifestList, deleteManifestById, batchSendManifestToSingleWindow } from '@/api/manifest.js'
import SearchExpand from '_c/search-expand'
import expandRow from './components/tableExpand.vue'
import importModal from './components/importModal'
import commonJS from './js/common'

export default {
    name: 'ManifestRoad',
    inject: ['nextPageReload'],
    components: {
        SearchExpand,
        // eslint-disable-next-line vue/no-unused-components
        expandRow,
        importModal
    },

    data () {
        return {
            searchData: {
                manifestType: '', // 舱单类型
                cargoBatchNo: '', // 批次号
                billNo: '', // 提运单号
                time1: [], // 申报时间
                time2: [], // 创建时间
                createStartTime: '',
                createEndTime: '',
                declStartTime: '',
                declEndTime: '',
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            loading: false,
            tableColumns: [
                {
                    type: 'expand',
                    width: 30,
                    render: (h, { index, row }) => {
                        return h(expandRow, {
                            props: {
                                list: row.consignmentVoList
                            },
                            on: {
                                'on-selection-change': (data) => {
                                    const status = data.length === row.consignmentVoList.length
                                    if (status) {
                                        this.handleAllSelectConsignment(index, status)
                                    } else if (data.length === 0) {
                                        this.handleAllSelectConsignment(index, status)
                                    } else {
                                        const ids = data.map(item => item.consignmentId)
                                        this.tableList[index]._checked = false
                                        this.tableList[index].consignmentVoList.forEach(item => {
                                            item._checked = ids.includes(item.consignmentId)
                                        })
                                    }
                                }
                            }
                        })
                    }
                },
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '舱单类型',
                    key: 'manifestType',
                    align: 'center',
                    width: 100,
                    render: (h, params) => {
                        return h(
                            'span',
                            this.manifestTypeList[params.row.manifestType]
                        )
                    }
                },
                {
                    title: '批次号',
                    key: 'cargoBatchNo',
                    align: 'center',
                    width: 100,
                    render: (h, params) => {
                        return h('div', [
                            h('span', [
                                h('Poptip', {
                                    props: {
                                        trigger: 'hover',
                                        confirm: false,
                                        content: params.row.cargoBatchNo,
                                        size: 'small'
                                    },
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }
                                }, params.row.cargoBatchNo)
                            ])
                        ])
                    }
                },
                {
                    title: '传输人名称',
                    key: 'representativePerson',
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('span', [
                                h('Poptip', {
                                    props: {
                                        trigger: 'hover',
                                        confirm: false,
                                        content: params.row.representativePerson,
                                        size: 'small'
                                    },
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }
                                }, params.row.representativePerson)
                            ])
                        ])
                    }
                },
                {
                    title: '进出境口岸',
                    key: 'iePortName',
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('span', [
                                h('Poptip', {
                                    props: {
                                        trigger: 'hover',
                                        confirm: false,
                                        content: params.row.iePortName,
                                        size: 'small'
                                    },
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }
                                }, params.row.iePortName)
                            ])
                        ])
                    }
                },
                {
                    title: '装载时间',
                    key: 'loadingDate',
                    align: 'center',
                    width: 150,
                    render: (h, params) => {
                        return h('div', [
                            h('span', [
                                h('Poptip', {
                                    props: {
                                        trigger: 'hover',
                                        confirm: false,
                                        content: params.row.loadingDate,
                                        size: 'small'
                                    },
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }
                                }, params.row.loadingDate)
                            ])
                        ])
                    }
                },
                {
                    title: '创建时间',
                    key: 'createTime',
                    align: 'center',
                    width: 150,
                    render: (h, params) => {
                        return h('div', [
                            h('span', [
                                h('Poptip', {
                                    props: {
                                        trigger: 'hover',
                                        confirm: false,
                                        content: params.row.createTime,
                                        size: 'small'
                                    },
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }
                                }, params.row.createTime)
                            ])
                        ])
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    fixed: 'right',
                    width: 80,
                    render: (h, params) => {
                        return h('div', [
                            h('i', {
                                'class': ['table-icon t-edit-icon'],
                                attrs: {
                                    title: '编辑'
                                },
                                on: {
                                    click: () => {
                                        this.toManifestRoad(params.row.manifestType, params.row.manifestId)
                                    }
                                }
                            }),
                            h('i', {
                                'class': ['table-icon t-del-icon'],
                                attrs: {
                                    title: '删除'
                                },
                                on: {
                                    click: () => {
                                        this.handleDelManifest(params.row.manifestId)
                                    }
                                }
                            })
                        ])
                    }
                }
            ],
            tableList: [],

            manifestTypeList: {
                'MT1401': '原始舱单',
                'MT2401': '预配舱单'
            },
            errorVisible: false,
            errorType: '',
            erorList: [],
            erorColumns: [
                {
                    title: '批次号/提（运）单号',
                    align: 'center',
                    key: 'relNo'
                },
                {
                    title: '表名',
                    key: 'className',
                    align: 'center'
                },
                {
                    title: '字段名',
                    key: 'fieldName',
                    align: 'center',
                    tooltip: true
                },
                {
                    title: '错误原因',
                    key: 'message',
                    align: 'center',
                    tooltip: true
                }
            ],
            continueLoading: false,
            resultModal: {
                visible: false,
                title: '申报成功',
                failInenerNo: '',
                failNum: 0,
                successNum: 0
            }
        }
    },

    created () {
        this.getData()
    },

    methods: {
        time1Change (daterange) {
            this.searchData.time1 = daterange
        },

        time2Change (daterange) {
            this.searchData.time2 = daterange
        },

        // 重新查询数据
        reGetData () {
            this.getData()
        },

        // 查询数据
        getData () {
            this.searchData.pageNum = 1
            this.searchData.pageSize = 10
            this.queryManifestList()
        },

        queryManifestList () {
            let search = {
                manifestType: this.searchData.manifestType,
                cargoBatchNo: this.searchData.cargoBatchNo,
                billNo: this.searchData.billNo,
                pageNum: this.searchData.pageNum,
                pageSize: this.searchData.pageSize,
                practicalTrainingId: this.$route.params.trainingId
            }

            if (Array.isArray(this.searchData.time1) && this.searchData.time1[0]) {
                search.declStartTime = commonJS.formatTimeToUnix(this.searchData.time1[0])
                search.declEndTime = commonJS.formatTimeToUnix(this.searchData.time1[1]) + 86400000 - 1
            } else {
                search.declStartTime = ''
                search.declEndTime = ''
            }

            if (Array.isArray(this.searchData.time2) && this.searchData.time2[0]) {
                search.createStartTime = commonJS.formatTimeToUnix(this.searchData.time2[0])
                search.createEndTime = commonJS.formatTimeToUnix(this.searchData.time2[1]) + 86400000 - 1
            } else {
                search.createStartTime = ''
                search.createEndTime = ''
            }
            search.transportType = 3
            this.loading = true
            getManifestList(search).then(res => {
                this.loading = false
                if (res.data.success) {
                    this.tableList = res.data.data.list.map(item => { // 为数组添加 _expanded 属性
                        let obj = {
                            _expanded: false,
                            _checked: false,
                            manifestId: item.manifestId,
                            manifestType: item.manifestType,
                            cargoBatchNo: item.cargoBatchNo,
                            representativePerson: item.representativePerson,
                            iePortName: item.iePortName,
                            loadingDate: item.loadingDate,
                            createTime: item.createTime
                        }
                        obj.consignmentVoList = item.consignmentVoList.map(csg => {
                            return {
                                _checked: false,
                                consignmentId: csg.consignmentId,
                                billNo: csg.billNo,
                                consignmentStatus: csg.consignmentStatus,
                                totalPackageQuantity: csg.totalPackageQuantity,
                                totalGrossMeasure: csg.totalGrossMeasure,
                                cargoValue: csg.cargoValue,
                                amountType: csg.amountType,
                                noticeMessage: csg.noticeMessage,
                                amountTypeName: csg.amountTypeName
                            }
                        })
                        return obj
                    })
                    this.searchData.total = res.data.data.total
                } else {
                    this.tableList = []
                }
            })
        },

        // 始终只有一项展开
        expandHandle (row, status) {
            let currentIndex = ''
            this.tableList.forEach((item, index) => {
                if (item.manifestId === row.manifestId) {
                    currentIndex = index // 获得当前操作数据的下标
                }
                this.$set(item, '_expanded', false)
            })
            this.tableList[currentIndex]._expanded = status
            let tempArr = JSON.stringify(this.tableList)
            this.tableList = []
            this.tableList = JSON.parse(tempArr)
        },

        // 新增原始舱单
        addOriginal () {
            this.nextPageReload()
            this.$router.push({
                name: 'rmftOriginAdd'
            })
        },

        // 新增预配舱单
        addPreplan () {
            this.nextPageReload()
            this.$router.push({
                name: 'rmftPreplanAdd'
            })
        },

        // 导入
        importHandle () {
            this.$refs.importModalRef.init(this.$route.params.trainingId)
        },

        toManifestRoad (manifestType, manifestId) {
            let routerName = manifestType === 'MT2401' ? 'rmftPreplanEdit' : 'rmftOriginEdit'
            this.nextPageReload()
            this.$router.push({
                name: routerName,
                params: {
                    manifestId: manifestId
                }
            })
        },
        // 删除舱单
        handleDelManifest (manifestId) {
            this.$Modal.confirm({
                title: '删除舱单',
                content: '确认删除该舱单？',
                loading: true,
                onOk: _ => {
                    deleteManifestById(manifestId).then(res => {
                        if (res.data.success) {
                            this.$Modal.remove()
                            this.queryManifestList()
                            this.$Message.success('删除成功')
                        } else {
                            this.$Modal.remove()
                            this.$Message.warning(res.data.msg)
                        }
                    }).catch(err => {
                        this.$Modal.remove()
                    })
                }
            })
        },
        // 获取申报数据
        getBatchData (continueFlag = '') {
            let arr = []
            const functionCode = 9 // 申报标识
            this.tableList.forEach(item => {
                const list = item.consignmentVoList.filter(cv => cv._checked).map(item => item.consignmentId)
                if (list.length) {
                    const obj = {
                        functionCode,
                        manifestId: item.manifestId,
                        consignmentIds: list.join(',')
                    }
                    continueFlag && (obj.continueFlag = continueFlag)
                    arr.push(obj)
                }
            })
            if (arr.length <= 0) return null
            return {
                continueFlag: continueFlag,
                functionNo: functionCode,
                requstSingleVoList: arr
            }
        },
        // 处理批量申报
        handleBatchDeclaration () {
            this.$Modal.confirm({
                title: '是否批量申报？',
                content: '确认申报选中的提运单号？',
                loading: true,
                onOk: () => {
                    const arr = this.getBatchData()
                    if (arr) {
                        batchSendManifestToSingleWindow(arr).then(res => {
                            if (res.data.success) {
                                this.$Modal.remove()
                                this.openBatchResult(res.data.data)
                            } else {
                                this.openBatchErrorModal(res.data.data.list, res.data.data.grade)
                                this.$Message.warning(res.data.msg)
                                this.$Modal.remove()
                            }
                        }).catch(err => {
                            this.$Modal.remove()
                        })
                    } else {
                        this.$Modal.remove()
                        this.$Message.warning('请选择需要申报的提运单号')
                    }
                }
            })
        },
        // 继续申报
        carryOnBatchDeclaration () {
            this.continueLoading = true
            const arr = this.getBatchData('Y')
            batchSendManifestToSingleWindow(arr).then(res => {
                if (res.data.success) {
                    this.openBatchResult(res.data.data)
                    this.errorVisible = false
                } else {
                    this.openBatchErrorModal(res.data.data.list, res.data.data.grade)
                    this.$Message.warning(res.data.msg)
                }
                this.continueLoading = false
            }).catch(err => {
                this.continueLoading = false
            })
        },
        // 打开批量申报错误弹窗
        openBatchErrorModal (errs, type) {
            this.erorList = errs
            this.errorType = type
            this.errorVisible = true
        },
        // 申报成功打开结果 展示成功条数和失败条数
        openBatchResult (data) {
            this.resultModal.visible = true
            this.resultModal.title = data.failNum > 0 ? '舱单申报结果' : '舱单申报成功'
            this.resultModal.failInenerNo = data.failCargoBatchNo
            this.resultModal.failNum = data.failNum || 0
            this.resultModal.successNum = data.succNum || 0
        },
        // 关闭批量申报结果弹窗
        closeResultModal () {
            this.resultModal.visible = false
            this.queryManifestList()
        },
        // 处理table复选框选择一个时 设置 提运单选择状态
        setSelectValue (selection, row, status) {
            const index = this.tableList.findIndex(item => item.manifestId === row.manifestId)
            this.tableList[index]._checked = status
            this.tableList[index].consignmentVoList.forEach(item => {
                item._checked = status
            })
        },
        // 处理单个复选框选中
        handleTableSelect (selection, row) {
            this.setSelectValue(selection, row, true)
        },
        // 处理单个复选框取消选中
        handleTableSelectCancel (selection, row) {
            this.setSelectValue(selection, row, false)
        },
        // 处理选中或者取消选中所有提运单
        handleAllSelectConsignment (index, status) {
            this.tableList[index]._checked = status
            this.tableList[index].consignmentVoList.forEach(item => {
                item._checked = status
            })
        },
        // 设置所有舱单选中或者取消选中状态
        setAllSelectValue (status) {
            this.tableList.forEach(item => {
                item._checked = status
                item.consignmentVoList.forEach(cv => {
                    cv._checked = status
                })
            })
        },
        // 处理表格复选框改变
        handleTableSelectChange (data) {
            if (data.length === this.tableList.length) {
                this.setAllSelectValue(true)
            } else if (data.length === 0) {
                this.setAllSelectValue(false)
            }
        }
    } // methods end
}
</script>

<style lang="less">
    .manifest-list {
        td.ivu-table-expanded-cell {
            padding: 0 20px 0 30px !important;
            background: #fff;
        }
    }
</style>
<style lang="less" scoped>
.result-modal-header {
    padding: 6px 0;
    &-title {
        display: inline-block;
        vertical-align: middle;
        margin-left: 12px;
        font-size: 16px;
        color: #17233d;
        font-weight: 700;
    }
}
.result-modal-content {
    padding: 5px 0 5px 42px;
    font-size: 14px;
    white-space:normal;
    word-break: break-word;
    p + p {
        margin-top: 6px;
    }
    .success {
        color: #19be6b;
    }
    .error {
        color: #ed4014;
    }
}
.result-modal-content-footer {
    text-align: right;
    padding-top: 15px;
}
</style>
